package com.ywd.platform.scheduler;

import com.ywd.platform.entity.VehicleTrackRecordEntity;
import com.ywd.platform.service.impl.DeviceServiceImpl;
import com.ywd.platform.service.impl.VehicleTrackRecordServiceImpl;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.util.List;

/**
 * YWD
 * 2025/9/1
 */
@AllArgsConstructor
@Slf4j
@Component
public class DeviceScheduler {

    private final DeviceServiceImpl  deviceService;
    private final VehicleTrackRecordServiceImpl vehicleTrackRecordService;


    @Async
    @Scheduled(cron = "0/50 * * * * ?")
    public void deviceScheduled() {
        log.info("设备心跳检测");
        //查询所有设备(只查询在线的)
        List<Long> list = deviceService.getListToDeviceScheduler();
        if(CollectionUtils.isEmpty(list)){
            return;
        }
        //更新设备状态
        list.forEach(deviceId -> {
            //当前时间 - 设备的最后上线时间 > 10s -- 离线
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime time = now.minusSeconds(150);
            List<VehicleTrackRecordEntity> list1 = vehicleTrackRecordService.getRecordTimeToDeviceScheduler(deviceId, time);
            if(CollectionUtils.isEmpty(list1)){
                deviceService.updateOnlineStatusById(deviceId);
            }
        });
    }

}
